#include <iostream>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "Protocol.hpp"
#include "log.hpp"
using namespace log_ns;

enum
{
    SOCKERROR = 1,
    CONNECTERROR
};

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << "Usage: " << argv[0] << " server-ip, server-port" << std::endl;
        exit(0);
    }

    std::string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);

    int sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd == -1)
    {
        LOG(FATAL, "socket error!\n");
        exit(SOCKERROR);
    }
    LOG(INFO, "socket success!\n");

    struct sockaddr_in ser_addr;
    memset(&ser_addr, 0, sizeof(ser_addr));
    ser_addr.sin_family = AF_INET;
    ser_addr.sin_port = htons(server_port);
    ::inet_pton(AF_INET, server_ip.c_str(), &ser_addr.sin_addr);

    int n = ::connect(sockfd, (struct sockaddr *)&ser_addr, sizeof(ser_addr));
    if (n == -1)
    {
        LOG(FATAL, "connect error!\n");
        exit(CONNECTERROR);
    }

    while (true)
    {
        std::string message;
        int x, y;
        char oper;

        std::cout << "input x: ";
        std::cin >> x;
        std::cout << "input y: ";
        std::cin >> y;
        std::cout << "input oper: ";
        std::cin >> oper;

        Request req(x, y, oper);
        req.Serialization(message);

        Encode(message);

        ::send(sockfd, message.c_str(), message.size(), 0);

        char echo_buffer[1024];

        int m = recv(sockfd, echo_buffer, sizeof(echo_buffer) - 1, 0);
        if (m > 0)
        {
            echo_buffer[m] = 0;
            std::string package = echo_buffer;
            std::string content;

            Decode(package, &content);

            Response resp;
            resp.Deserialization(content);
            std::cout<<resp.Result()<<"["<<resp.Code()<<"]"<<std::endl;
        }
        else
        {
            break;
        }
    }

    ::close(sockfd);
    return 0;
}